package org.example.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @Author: tang
 * @Description: DataSet API
 * @Date 2025/2/14 10:25
 */
public class FlinkWordCountBatchMain {

    public static void main(String[] args) throws Exception {

        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();

        DataSource<String> dataSource = executionEnvironment.readTextFile("/Users/tanglonglong/idea_project" +
                "/cloud-test/web-springboot/flink/src/main/resources/words.txt");
        FlatMapOperator<String, Tuple2<String, Integer>> flatMapOperator = dataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String key, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = key.split(" ");
                for (String word : words) {
                    collector.collect(new Tuple2<String, Integer>(word, 1));
                }
            }
        });
        AggregateOperator<Tuple2<String, Integer>> sum = flatMapOperator.groupBy(0).sum(1);
        sum.print();
    }

}
